<?PHP
/**
 * 提交之后系统调用代码到AX数据CRONTAB
 *
 * @author chenping@shopex.cn
 * @version $2012-8-13 15:33Z
 */
class wms_autotask_task_syncoms
{

    function __construct($app)
    {
        $this->app = $app;
        $this->db = kernel::database();
    }

    /**
     * @description
     * @access public
     * @param void
     * @return void
     */
    public function error($log_id,$logi_no,$msg,$failNum)
    {
    }

    /**
     * @description
     * @access public
     * @param void
     * @return void
     */
    public function success($log_id,$logi_no,$succNum)
    {
    }

    /**
     * @description 执行批量发货
     * @access public
     * @param void
     * @return void
     */
    public function process($params, &$error_msg='')
    {
        
        error_log(date('Y-m-d H:i:s').'发送数据/'.var_export($logiNoList,true),3,DATA_DIR.'/autodlycomp'.date('Y-m-d').'.log');
        if( (!$params['log_id']) || (!$params['log_text']) ){
            return false;
        }else{
            $params['log_text'] = unserialize($params['log_text']);
        }
        
        set_time_limit(240);

        $this->exec_syncoms($params['log_id'],$params['log_text']);
        return true;
    }

    /**
     * @执行同步发货操作
     * @access public
     * @param void
     * @return void
     */
    public function exec_syncoms($log_id,$logiNoList)
    {
        if (empty($logiNoList) || !is_array($logiNoList) || !$log_id) return false;

        $now = time();
        $logiNoList = array_filter($logiNoList);

    	error_log(date('Y-m-d H:i:s').'发送数据/'.var_export($logiNoList,true),3,DATA_DIR.'/autodlycomp'.date('Y-m-d').'.log');

    }
    
    /**
     * @执行发货完成同步发货动作，分批次过数到AX(100条一次)
     * @access public
     * @param void
     * @return void
     */
    public function dosync($id)
    {
        date_default_timezone_set("PRC");
        ini_set('soap.wsdl_cache_enabled', "0"); //关闭wsdl缓存
        ini_set('default_socket_timeout', 5000); // timeout
        ini_set('memory_limit', '512M');
        set_time_limit(1000);
        $db=kernel::database();
        //1.根据发货完成ID，区分本次有多少次循环
        $datacounts=$this->getdeliverycounts($id);
        if(count($datacounts)>0)
        {
            foreach ($datacounts as $key => $value) 
            {
                //2.根据订单号及发货单号，获取过数明细
                $msg = '';
                $deliveryInfo= $this->getdeliveryinfo($id,$value['axorderno'],$value['axshipno']);
                if(count($deliveryInfo)<1)
                    continue;
                $xml='';
                foreach ($deliveryInfo as $k => $v) 
                {
                    //add by ldward 20181121 如果为经销商类型，则必须校验价格异常
                    if($v['leemantype']!='3')
                    {
                        if($v['divide_order_fee']<=0)
                        {
                            //记录到日志中
                            $msg=$v['delivery_bn'].'发货单价格存在异常！';
                            break;
                        }
                    }
                    $SalesPrice=round($v['divide_order_fee']/$v['nums'],4);
                    //唯一值
                    $tmp = $v['AXCustomer'] .'-'.$v['shop_bn'].'-' . $v['bn'] . '-' . $SalesPrice . '-' . $v['unit'] . '-' . $v['axshipno'] . '-' . $v['axorderno'] . '-' . $v['carno'];
                    $salesPlatfrom = '其他';
                    if ($v['shop_type'] != '') 
                    {
                        $salesPlatfrom = ome_shop_type::shop_name($v['shop_type']);
                    }
                    if (isset($number_tmp[$tmp])) {
                        $number_tmp[$tmp] += $v['number'];
                    } else {
                        $number_tmp[$tmp] = $v['number'];
                    }
                    $xml[$tmp] = '<Cust>'
                        . '<CustAccount>' . $v['AXCustomer'] . '</CustAccount>'
                        . '<ItemId>' . $v['bn'] . '</ItemId>'
                        . '<SalesPrice>' . $SalesPrice . '</SalesPrice>'
                        . '<SalesQty>' . $number_tmp[$tmp]. '</SalesQty>'
                        . '<SalesUnit>' . $v['unit'] . '</SalesUnit>'
                        . '<PackingSlipId>' . $v['axshipno'] . '</PackingSlipId>'
                        . '<SalesId>' . $v['axorderno'] . '</SalesId>'
                        . '<LicencePlateNo>' . $v['carno'] . '</LicencePlateNo>'
                        . '<shopName>' . $v['shop_bn'] . '</shopName>'
                        . '<salesPlatfrom>' . $salesPlatfrom . '</salesPlatfrom>'
                        . '</Cust>';
                }
                if(!empty($msg))
                {
                    $db->exec("update sdb_wms_deliverynote_line set msg='".$msg."',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                    continue;
                }
                $rel_xml='';
                //3.拼接xml明细传入到AX
                foreach ($xml as $key => $value) 
                {
                    $rel_xml .= $value;
                }
                //4. 过数
                try {
                    $param['str'] = "<CustGroup>".$rel_xml."<Attribute><IsCreatePickingRoute>yes</IsCreatePickingRoute></Attribute></CustGroup>";
                    $param['company'] = $value['srcorg'];
                    $res=kernel::single('erpapi_rpc_qimen')->call('CreateSalesOrder',$param);
                    $res=json_decode($res,1);
                    if (isset($res['response']['data']) && !empty($res['response']['data'])) 
                    {
                        $arr = json_decode($res['response']['data'], '1');
                        if (count($arr) > 0) 
                        {
                            $axorderno='';
                            foreach ($arr as $key => $value) 
                            {    
                                if($value['Code'] == '0' || ($value['Code'] == '99' && (strpos($value['Msg'],"该记录已存在") != false) ))
                                {
                                    $db->exec("update sdb_wms_deliverynote_line set status ='confirmed',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                                }else
                                {
                                    $msg .= "(" . $value['Msg'] . ")";
                                    $db->exec("update sdb_wms_deliverynote_line set msg='".$value['Msg']."',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                                }
                            }
                        }else{
                            $msg.=$res['response']['data'];
                            $db->exec("update sdb_wms_deliverynote_line set msg='".$res['response']['data']."',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                        }
                    }else{
                        $msg.='奇门接口异常：'.json_encode($res['response']);
                        $db->exec("update sdb_wms_deliverynote_line set msg='".'奇门接口异常：'.json_encode($res['response'])."',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                    }
                }catch (Exception $e) 
                {
                    $msg.='接口出错：' . $e->getMessage();
                    $db->exec("update sdb_wms_deliverynote_line set msg='".'接口出错：'.$e->getMessage()."',last_modify=".time()." where axorderno = '".$value['AxOrderNo']."' ");
                }
            }
        }
        //5.更新发货完成状态
        if (empty($msg) && isset($msg)) 
        {
            $db->exec("update sdb_wms_deliverycomp set status='confirmed',last_modify=".time()." where id in(".$id.")");
        }
    }
    /**
     * @根据发货完成获取ID
     * @access public
     * @param void
     * @return void
     */
    public function getdeliverycounts($dc_id)
    {
        $db=kernel::database();
        $sql = "SELECT distinct axshipno ,axorderno,dc.srcorg
            FROM sdb_wms_deliverycomp dc
            LEFT JOIN sdb_wms_deliverycomp_line dcl on (dc.id = dcl.deliverycomp_id)
            LEFT JOIN sdb_wms_deliverynote dn on (dcl.deliverynote_id = dn.id )
            LEFT JOIN sdb_wms_deliverynote_line dnl on ( dn.id = dnl.deliverynote_id )
            where dc.id = '$dc_id' and dnl.status='unconfirmed' ";
        $rows = $db->select($sql);
        return $rows;
    }
    /**
     * @根据发货完成获取ID
     * @access public
     * @param void
     * @return void
     */
    public function getdeliveryinfo($dc_id,$axorderno,$axshipno)
    {
        $db=kernel::database();
        $sql = "SELECT f.shop_bn,f.AXCustomer,f.shop_type,bmt.unit,its.bn,its.number,oits.divide_order_fee,oits.nums,dnl.axorderno,dnl.axshipno,d.carno,f.leemantype,d.delivery_bn
            FROM sdb_wms_deliverycomp dc
            inner JOIN sdb_wms_deliverycomp_line dcl on (dc.id = dcl.deliverycomp_id)
            inner JOIN sdb_wms_deliverynote dn on (dcl.deliverynote_id = dn.id )
            inner JOIN sdb_wms_deliverynote_line dnl on ( dn.id = dnl.deliverynote_id )
            inner JOIN sdb_wms_delivery d on (dnl.delivery_id = d.delivery_id)
            LEFT JOIN sdb_ome_delivery od on (od.delivery_bn=d.outer_delivery_bn)
            LEFT JOIN sdb_ome_delivery_order odo on (odo.delivery_id=od.delivery_id)
            inner join sdb_ome_shop f on d.shop_id=f.shop_id
            inner join sdb_wms_delivery_items its on d.delivery_id=its.delivery_id
            inner join sdb_ome_order_items oits on odo.order_id=oits.order_id and its.bn=oits.bn
            inner join sdb_material_basic_material bm on bm.material_bn=its.bn
            inner join sdb_material_basic_material_ext bmt on bm.bm_id=bmt.bm_id
            where dc.id = '$dc_id' and dnl.axorderno='$axorderno' and dnl.status='unconfirmed' and dnl.axshipno='$axshipno' and f.AXCustomer!=''";
            
        $rows = $db->select($sql);
        return $rows;
    }
}